package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.common.BusinessException;
import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.mapper.UserMapper;
import cn.wolfcode.shop.redis.MemberServerKeyPrefix;
import cn.wolfcode.shop.redis.RedisTemplate;
import cn.wolfcode.shop.service.IUserService;
import cn.wolfcode.shop.util.CookieUtil;
import cn.wolfcode.shop.util.MD5Util;
import cn.wolfcode.shop.web.result.MemberServerCodeMsg;
import cn.wolfcode.shop.web.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public User get(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public String login(LoginVo loginVo) {
        User user = this.get(Long.parseLong(loginVo.getUsername()));
        if (user == null){
            throw new BusinessException(MemberServerCodeMsg.LOGIN_ERROR);
        }
        String salt = user.getSalt();
        String dbPass = MD5Util.formPassToDbPass(loginVo.getPassword(), salt);
        if (!user.getPassword().equals(dbPass)){
            throw new BusinessException(MemberServerCodeMsg.LOGIN_ERROR);
        }
        // 创建token
        String token = createToken(user);
        return token;
    }

    public Boolean refreshToken(String token) {
        if(redisTemplate.exists(MemberServerKeyPrefix.USER_TOKEN,token)){
            if(redisTemplate.expire(MemberServerKeyPrefix.USER_TOKEN,token, CookieUtil.TOKEN_EXPIRE_SECONDS)>0){
                return true;
            }
        }
        return false;
    }

    public User getCurrent(String token) {
        return redisTemplate.get(MemberServerKeyPrefix.USER_TOKEN,token,User.class);
    }

    private String createToken(User user) {

        String token = UUID.randomUUID().toString().replace("-","");
        redisTemplate.set(MemberServerKeyPrefix.USER_TOKEN, token, user);
        return token;
    }
}

